<template>
  <page-header-wrapper @back="back">
    <template v-slot:breadcrumb>
      {{ formTitle }}
    </template>
    <template v-slot:title>
      {{ formTitle }}
    </template>
    <template v-slot:content>
    </template>
    <template v-slot:extraContent>
    </template>
    <a-result title="请至少选择一个表修改" v-if="!tableName">
      <template #icon>
        <a-icon type="smile" theme="twoTone" />
      </template>
      <template #extra>
        <a-button type="primary" @click="back">
          返回生成页
        </a-button>
      </template>
    </a-result>
    <a-card :bordered="false" v-if="tableName != 0">
      <a-tabs default-active-key="2">
        <a-tab-pane key="1" tab="基本信息" force-render>
          <basic-info-form ref="basicInfo" :info="info" />
        </a-tab-pane>
        <a-tab-pane key="2" tab="字段信息" force-render>
          <!-- 表格 -->
          <a-table
            ref="table"
            size="small"
            :columns="columns"
            :loading="tableLoading"
            :data-source="columnList"
            row-key="columnId"
            :pagination="false"
          >
            <!-- 字段名 -->
            <template slot="columnName" slot-scope="text, record">
              <a-input v-model="record.columnName" placeholder="请使用下划线方式命名"></a-input>
            </template>
            <!-- 字段描述 -->
            <template slot="columnComment" slot-scope="text, record">
              <a-input v-model="record.columnComment"></a-input>
            </template>
            <!-- 最大长度 -->
            <template slot="columnLength" slot-scope="text, record">
              <a-input-number v-model="record.columnLength" :min="1"></a-input-number>
            </template>
            <!-- 插入 -->
            <template slot="isInsert" slot-scope="text, record">
              <a-checkbox v-model="record.isInsert" ></a-checkbox>
            </template>
            <!-- 编辑 -->
            <template slot="isEdit" slot-scope="text, record">
              <a-checkbox v-model="record.isEdit"></a-checkbox>
            </template>
            <!-- 列表 -->
            <template slot="isList" slot-scope="text, record">
              <a-checkbox v-model="record.isList"></a-checkbox>
            </template>
            <!-- 查询 -->
            <template slot="isQuery" slot-scope="text, record">
              <a-checkbox v-model="record.isQuery"></a-checkbox>
            </template>
            <!-- 查询方式 -->
            <template slot="queryType" slot-scope="text, record">
              <a-select v-model="record.queryType" style="width:100%">
                <a-select-option value="EQ">=</a-select-option>
                <a-select-option value="NE">!=</a-select-option>
                <a-select-option value="GT">></a-select-option>
                <a-select-option value="GTE">>=</a-select-option>
                <a-select-option value="LT">&lt;</a-select-option>
                <a-select-option value="LTE">&lt;=</a-select-option>
                <a-select-option value="LIKE">LIKE</a-select-option>
                <a-select-option value="BETWEEN">BETWEEN</a-select-option>
              </a-select>
            </template>
            <!-- 必填 -->
            <template slot="isRequired" slot-scope="text, record">
              <a-checkbox v-model="record.isRequired"></a-checkbox>
            </template>
            <!-- 显示类型 -->
            <template slot="htmlType" slot-scope="text, record">
              <a-select v-model="record.htmlType" style="width:100%">
                <a-select-option value="input">文本框</a-select-option>
                <a-select-option value="textarea">文本域</a-select-option>
                <a-select-option value="select">下拉框</a-select-option>
                <a-select-option value="radio">单选框</a-select-option>
                <a-select-option value="checkbox">复选框</a-select-option>
                <a-select-option value="datetime">日期控件</a-select-option>
                <a-select-option value="imageUpload">图片上传</a-select-option>
                <a-select-option value="fileUpload">文件上传</a-select-option>
                <a-select-option value="editor">富文本控件</a-select-option>
              </a-select>
            </template>
            <!-- 字典类型 -->
            <template slot="dictType" slot-scope="text, record">
              <a-select v-model="record.dictType" placeholder="请选择" style="width:100%">
                <a-select-option
                  v-for="item in dictOptions"
                  :key="item.dictType"
                  :value="item.dictType">
                  {{ item.dictName }}
                </a-select-option>
              </a-select>
            </template>
            <template slot="operation" slot-scope="text, record">
              <a @click="handleDelete(record)" v-hasPermi="['tool:gen:remove']" v-if="record.isPk !== '1'">
                <a-icon type="delete" />删除
              </a>
            </template>
          </a-table>
          <a-button type="dashed" block @click="handleAdd()" v-hasPermi="['tool:gen:add']" class="add-btn">
            <a-icon type="plus" />新增
          </a-button>
        </a-tab-pane>
        <a-tab-pane key="3" tab="生成信息" force-render>
          <gen-info-form ref="genInfo" :info="info" :tableSelect="tableSelect" :menus="menus"/>
        </a-tab-pane>
      </a-tabs>
      <a-form label-width="100px">
        <footer-tool-bar>
          <a-space>
            <a-button type="primary" @click="submitForm">
              保存
            </a-button>
            <a-button type="dashed" @click="back">
              取消
            </a-button>
          </a-space>
        </footer-tool-bar>
      </a-form>
    </a-card>

    <create-column-form ref="createForm"/>
  </page-header-wrapper>
</template>

<script>
import { getGenTable, updateGenTable, syncDb, delGenTableColumn } from '@/api/tool/gen'
import { optionSelect as getDictOptionSelect } from '@/api/system/dict/type'
import { listMenu as getMenuTreeselect } from '@/api/system/menu'
import BasicInfoForm from './BasicInfoForm'
import GenInfoForm from './GenInfoForm'
import CreateColumnForm from './CreateColumnForm'
export default {
  name: 'GenEdit',
  components: {
    BasicInfoForm,
    GenInfoForm,
    CreateColumnForm
  },
  data () {
    return {
      tableName: '',
      // 新增字段下标
      newId: 1,
      formTitle: '修改生成配置',
      // 表格加载
      tableLoading: false,
      // 字典信息
      dictOptions: [],
      // 菜单信息
      menus: [],
      // 表信息
      tableSelect: [],
      // 表详细信息
      info: {},
      // 表字段数据
      columnList: [],
      // 表头
      columns: [
        {
          title: '字段名',
          dataIndex: 'columnName',
          align: 'left',
          ellipsis: true,
          width: '10%',
          slots: { title: 'columnNameTitle' },
          scopedSlots: { customRender: 'columnName' }
        },
        {
          title: '字段描述',
          dataIndex: 'columnComment',
          scopedSlots: { customRender: 'columnComment' },
          align: 'left',
          width: '8%'
        },
        {
          title: '最大长度',
          dataIndex: 'columnLength',
          scopedSlots: { customRender: 'columnLength' },
          align: 'left',
          width: '8%'
        },
        {
          title: '插入',
          dataIndex: 'isInsert',
          scopedSlots: { customRender: 'isInsert' },
          align: 'center',
          width: '3%'
        },
        {
          title: '编辑',
          dataIndex: 'isEdit',
          scopedSlots: { customRender: 'isEdit' },
          align: 'center',
          width: '3%'
        },
        {
          title: '列表',
          dataIndex: 'isList',
          scopedSlots: { customRender: 'isList' },
          align: 'center',
          width: '3%'
        },
        {
          title: '查询',
          dataIndex: 'isQuery',
          scopedSlots: { customRender: 'isQuery' },
          align: 'center',
          width: '3%'
        },
        {
          title: '查询方式',
          dataIndex: 'queryType',
          scopedSlots: { customRender: 'queryType' },
          align: 'center',
          width: '10%'
        },
        {
          title: '必填',
          dataIndex: 'isRequired',
          scopedSlots: { customRender: 'isRequired' },
          align: 'center',
          width: '3%'
        },
        {
          title: '显示类型',
          dataIndex: 'htmlType',
          scopedSlots: { customRender: 'htmlType' },
          align: 'center',
          width: '10%'
        },
        {
          title: '字典类型',
          dataIndex: 'dictType',
          scopedSlots: { customRender: 'dictType' },
          align: 'center',
          width: '10%'
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: '10%',
          scopedSlots: { customRender: 'operation' },
          align: 'center'
        }
      ]
    }
  },
  created () {
    const tableName = this.$route.params && this.$route.params.tableName
    if (tableName) {
      this.tableName = tableName
    }
    this.tableLoading = true
    if (this.tableName) {
      // 获取表详细信息
      getGenTable(this.tableName).then(res => {
        const columnList = res.info.columns
        columnList.forEach(e => {
          e.isInsert = e.isInsert === '1'
          e.isEdit = e.isEdit === '1'
          e.isList = e.isList === '1'
          e.isQuery = e.isQuery === '1'
          e.isRequired = e.isRequired === '1'
        })
        this.columnList = columnList
        this.info = res.info
        this.tableSelect = res.tableSelect
        this.tableLoading = false
      })
      /** 查询字典下拉列表 */
      getDictOptionSelect().then(response => {
        this.dictOptions = response
      })
      /** 查询菜单下拉列表 */
      getMenuTreeselect().then(response => {
        this.menus = this.handleTree(response, 'menuId')
      })
    }
  },
  methods: {
    /** 添加按钮 **/
    handleAdd () {
      this.columnList.push({
        columnId: 'new-' + this.newId
      })
      this.newId++
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      if (row.columnId.toString().startsWith('new-')) {
        const columnList = this.columnList.filter(item => item.columnId !== row.columnId)
        this.columnList = columnList
        return
      }
      this.$confirm({
        title: '确认删除所选中数据?',
        content: `该操作将删除表【${this.tableName}】中的【${row.columnName}】字段，请谨慎操作！`,
        onOk: () => {
          return delGenTableColumn(row.columnId)
            .then(() => {
              const columnList = this.columnList.filter(item => item.columnId !== row.columnId)
              this.columnList = columnList
              this.$message.success(
                '删除成功',
                3
              )
            })
        },
        onCancel () {}
      })
    },
    /** 提交按钮 */
    submitForm () {
      const basicForm = this.$refs.basicInfo.info
      const genForm = this.$refs.genInfo.info

      if (basicForm && genForm) {
        const genTable = Object.assign({}, basicForm, genForm)
        const columnList = this.columnList
        columnList.forEach(e => {
          e.isInsert = e.isInsert ? '1' : '0'
          e.isEdit = e.isEdit ? '1' : '0'
          e.isList = e.isList ? '1' : '0'
          e.isQuery = e.isQuery ? '1' : '0'
          e.isRequired = e.isRequired ? '1' : '0'
        })
        genTable.columns = columnList
        genTable.params = {
          treeCode: genTable.treeCode,
          treeName: genTable.treeName,
          treeParentCode: genTable.treeParentCode,
          parentMenuId: genTable.parentMenuId
        }
        updateGenTable(genTable).then(res => {
          this.$message.success('保存成功')
        })
      } else {
        this.msgError('表单校验未通过，请重新检查提交内容')
      }
    },
    /** 关闭按钮 */
    back () {
      this.$router.push('/tool/gen')
    },
    /** 同步数据库操作 */
    handleSyncDb () {
      this.$confirm({
        title: '确认强制同步数据?',
        content: '当前同步表名为' + this.tableName + '的数据',
        onOk: () => {
          return syncDb(this.tableName)
            .then(() => {
              this.onSelectChange([], [])
              this.getList()
              this.$message.success(
                '同步成功',
                3
              )
            })
        },
        onCancel () {}
      })
    }
  }
}
</script>
<style scoped>
  .add-btn {
    margin-top: 20px;
  }
</style>
